#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>

#define BUFFER_SIZE 1025

int main()
{
    /*创建管道*/
    int pipeFd[2] = {0};
    int ret = pipe(pipeFd);
    if (ret == -1)
    {
        perror("pipe error:");
        _exit(-1);
    }

    /*创建子进程*/
    pid_t pid = fork();
    if (pid < 0)
    {
        perror("fork error:");
        exit(-1);
    }
    else if (pid == 0)
    {
        /*把写端关闭*/
        close(pipeFd[1]);
        /*子进程*/
        /*从管道里面读数据*/
        sleep(10);

        char buffer1[BUFFER_SIZE] = {0};
        int readBytes = read(pipeFd[0], buffer1, sizeof(buffer1) - 1); // read也是"阻塞函数"
        printf("%s\n", buffer1);


        sleep(3);
    }
    else
    {
        /*把读端关闭*/
        close(pipeFd[0]);
        /*父进程*/
        /*父进程写(1)，子进程读(0)*/

        // sleep(5); // 内核没有数据 会等10s之后再读写    
        // /*向管道里面写数据*/
        // int writeBytes = write(pipeFd[1], buffer, strlen(buffer));
        int cnt = 0;
        while (1)
        {
            usleep(100);
            char buffer[512];
            memset(buffer, 'a', sizeof(buffer));
            /*向管道里面写数据*/
            int writeBytes = write(pipeFd[1], buffer, strlen(buffer));
            if (writeBytes <= 0)
            {
               printf("here...");
            }
            
            printf("writeBytes:%d,cnt = %d\n",writeBytes,cnt);
            cnt++;
        }

#if 0
        char buf[BUFFER_SIZE] = {0};
        int readBytes = read(pipeFd[0], buf, sizeof(buffer));
        printf("parent readBytes = %d,buf = %s\n", readBytes, buf);
#endif

        /*阻塞回收等待子进程*/
        wait(NULL);
        printf("recycle success.\n");
    }
    return 0;
}

// 不是死循环时 通常是阻塞
// strace -p 24006 查询
